<template>
  <div class="private-chat">
    <div class="chat-layout">
      <!-- 聊天列表 -->
      <ChatList
        ref="chatListRef"
        :chats="chats"
        :current-user="currentUser"
        @select-chat="handleSelectChat"
        @new-chat="handleNewChat"
        @search-user="handleSearchUser"
      />
      
      <!-- 聊天窗口 -->
      <ChatWindow
        :current-chat="selectedChat"
        :current-user="currentUser"
        @send-message="handleSendMessage"
        @clear-chat="handleClearChat"
        @new-chat="handleNewChat"
      />
    </div>

    <!-- 新聊天对话框 -->
    <el-dialog
      v-model="showNewChatDialog"
      title="发起新聊天"
      width="500px"
      align-center
    >
      <div class="new-chat-dialog">
        <div class="search-section">
          <h4>搜索用户</h4>
          <div class="search-input-group">
            <el-input
              v-model="userSearchKeyword"
              placeholder="输入用户UID或用户名..."
              prefix-icon="Search"
              clearable
              @keyup.enter="searchUsers"
            />
            <el-button 
              type="primary" 
              @click="searchUsers"
              :loading="searchingUsers"
            >
              搜索
            </el-button>
          </div>
        </div>
        
        <div class="user-list">
          <div v-if="searchingUsers" class="loading-users">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>搜索中...</span>
          </div>
          
          <div
            v-for="user in searchedUsers"
            :key="user.id"
            class="user-item"
            @click="startChatWithUser(user)"
          >
            <el-avatar :size="40" :src="user.avatar" />
            <div class="user-info">
              <div class="user-main-info">
                <span class="user-name">{{ user.name }}</span>
                <el-tag 
                  :type="user.type === 'farmer' ? 'success' : 'primary'" 
                  size="small"
                >
                  {{ user.type === 'farmer' ? '农户' : '买家' }}
                </el-tag>
              </div>
              <div class="user-details">
                <span class="user-uid">UID: {{ user.id }}</span>
                <span class="user-status" :class="user.online ? 'online' : 'offline'">
                  {{ user.online ? '在线' : '离线' }}
                </span>
              </div>
            </div>
          </div>

          <div v-if="!searchingUsers && searchedUsers.length === 0 && userSearchKeyword" class="empty-users">
            <el-empty description="未找到用户" />
          </div>

          <div v-if="!searchingUsers && !userSearchKeyword" class="recent-users">
            <h4>最近联系</h4>
            <div
              v-for="user in recentUsers"
              :key="user.id"
              class="user-item"
              @click="startChatWithUser(user)"
            >
              <el-avatar :size="40" :src="user.avatar" />
              <div class="user-info">
                <div class="user-main-info">
                  <span class="user-name">{{ user.name }}</span>
                  <el-tag 
                    :type="user.type === 'farmer' ? 'success' : 'primary'" 
                    size="small"
                  >
                    {{ user.type === 'farmer' ? '农户' : '买家' }}
                  </el-tag>
                </div>
                <div class="user-details">
                  <span class="user-uid">UID: {{ user.id }}</span>
                  <span class="user-status" :class="user.online ? 'online' : 'offline'">
                    {{ user.online ? '在线' : '离线' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import ChatList from './ChatList.vue'
import ChatWindow from './ChatWindow.vue'

// 当前用户信息
const currentUser = ref({
  id: 10001,
  name: '当前用户',
  avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
  type: 'buyer'
})

// 聊天列表数据
const chats = ref([
  {
    id: 1,
    type: 'private',
    participant: {
      id: 10002,
      name: '张大山',
      avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
      type: 'farmer',
      online: true
    },
    lastMessage: {
      content: '您好，我对您的西红柿很感兴趣',
      type: 'text',
      timestamp: '2024-01-15T14:30:00Z'
    },
    lastMessageTime: '2024-01-15T14:30:00Z',
    unreadCount: 2,
    messages: [
      {
        id: 1,
        type: 'text',
        content: '您好，请问您的西红柿怎么卖？',
        senderId: 10002,
        senderName: '张大山',
        senderAvatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
        timestamp: '2024-01-15T14:25:00Z',
        status: 'sent'
      },
      {
        id: 2,
        type: 'text',
        content: '您好，我们的西红柿是15元/斤，都是有机种植的',
        senderId: 10001,
        senderName: '当前用户',
        senderAvatar: currentUser.value.avatar,
        timestamp: '2024-01-15T14:28:00Z',
        status: 'sent'
      },
      {
        id: 3,
        type: 'text',
        content: '好的，我对您的西红柿很感兴趣',
        senderId: 10002,
        senderName: '张大山',
        senderAvatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
        timestamp: '2024-01-15T14:30:00Z',
        status: 'sent'
      }
    ]
  }
])

// 用户列表数据
const allUsers = ref([
  {
    id: 10002,
    name: '张大山',
    avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
    type: 'farmer',
    online: true
  },
  {
    id: 10003,
    name: '李超市',
    avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
    type: 'buyer',
    online: false
  },
  {
    id: 10004,
    name: '王农场',
    avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
    type: 'farmer',
    online: true
  },
  {
    id: 10005,
    name: '赵生鲜',
    avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
    type: 'buyer',
    online: true
  }
])

const selectedChat = ref(null)
const showNewChatDialog = ref(false)
const userSearchKeyword = ref('')
const searchingUsers = ref(false)
const chatListRef = ref(null)
const searchedUsers = ref([])

// 最近联系用户
const recentUsers = computed(() => {
  return allUsers.value.filter(user => 
    chats.value.some(chat => 
      chat.type === 'private' && chat.participant.id === user.id
    )
  ).slice(0, 5)
})

// 搜索用户
const searchUsers = async () => {
  if (!userSearchKeyword.value.trim()) {
    ElMessage.warning('请输入用户UID或用户名')
    return
  }

  searchingUsers.value = true
  try {
    // 模拟API搜索
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const keyword = userSearchKeyword.value.trim().toLowerCase()
    searchedUsers.value = allUsers.value.filter(user => 
      user.name.toLowerCase().includes(keyword) || 
      user.id.toString().includes(keyword)
    )
    
    if (searchedUsers.value.length === 0) {
      ElMessage.info('未找到相关用户')
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    searchingUsers.value = false
  }
}

// 处理搜索用户（从ChatList触发）
const handleSearchUser = async (keyword) => {
  searchingUsers.value = true
  try {
    // 模拟API搜索
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const foundUser = allUsers.value.find(user => 
      user.id.toString() === keyword || 
      user.name.toLowerCase().includes(keyword.toLowerCase())
    )
    
    if (foundUser) {
      // 在ChatList中显示搜索结果
      chatListRef.value?.setSearchResult(foundUser)
    } else {
      ElMessage.info('未找到用户')
      chatListRef.value?.setSearchResult(null)
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    searchingUsers.value = false
  }
}

// 选择聊天
const handleSelectChat = (chat) => {
  selectedChat.value = chat
  // 标记为已读
  chat.unreadCount = 0
}

// 发送消息
const handleSendMessage = async (messageData) => {
  if (!selectedChat.value) return
  
  // 模拟发送消息
  const newMessage = {
    ...messageData,
    status: 'sent'
  }
  
  selectedChat.value.messages.push(newMessage)
  selectedChat.value.lastMessage = newMessage
  selectedChat.value.lastMessageTime = newMessage.timestamp
  
  // 模拟对方回复（演示用）
  setTimeout(() => {
    const replyMessage = {
      id: Date.now(),
      type: 'text',
      content: getAutoReplyMessage(selectedChat.value.participant.type),
      senderId: selectedChat.value.participant.id,
      senderName: selectedChat.value.participant.name,
      senderAvatar: selectedChat.value.participant.avatar,
      timestamp: new Date().toISOString(),
      status: 'sent'
    }
    
    selectedChat.value.messages.push(replyMessage)
    selectedChat.value.lastMessage = replyMessage
    selectedChat.value.lastMessageTime = replyMessage.timestamp
    selectedChat.value.unreadCount += 1
  }, 2000)
}

// 获取自动回复消息
const getAutoReplyMessage = (userType) => {
  const messages = {
    farmer: [
      '收到您的消息，我会尽快安排发货',
      '感谢您的咨询，我们的产品都是有机种植的',
      '好的，我确认一下库存后回复您'
    ],
    buyer: [
      '收到消息，我会认真考虑您的报价',
      '感谢您的订单，期待长期合作',
      '好的，我查看一下需求后回复您'
    ]
  }
  const userMessages = messages[userType] || messages.buyer
  return userMessages[Math.floor(Math.random() * userMessages.length)]
}

// 清空聊天
const handleClearChat = (chatId) => {
  const chat = chats.value.find(c => c.id === chatId)
  if (chat) {
    chat.messages = []
    chat.lastMessage = null
    chat.lastMessageTime = null
    chat.unreadCount = 0
  }
  
  if (selectedChat.value && selectedChat.value.id === chatId) {
    selectedChat.value = null
  }
}

// 发起新聊天
const handleNewChat = (user = null) => {
  if (user) {
    startChatWithUser(user)
  } else {
    showNewChatDialog.value = true
    userSearchKeyword.value = ''
    searchedUsers.value = []
  }
}

// 与用户开始聊天
const startChatWithUser = (user) => {
  // 检查是否已有聊天
  const existingChat = chats.value.find(chat => 
    chat.type === 'private' && chat.participant.id === user.id
  )
  
  if (existingChat) {
    selectedChat.value = existingChat
    existingChat.unreadCount = 0
  } else {
    // 创建新聊天
    const newChat = {
      id: Date.now(),
      type: 'private',
      participant: user,
      lastMessage: null,
      lastMessageTime: null,
      unreadCount: 0,
      messages: []
    }
    
    chats.value.unshift(newChat)
    selectedChat.value = newChat
    
    // 添加系统欢迎消息
    const welcomeMessage = {
      id: Date.now() + 1,
      type: 'system',
      content: '您已开始与对方聊天，现在可以发送消息了',
      senderId: 'system',
      timestamp: new Date().toISOString(),
      status: 'sent'
    }
    
    newChat.messages.push(welcomeMessage)
  }
  
  showNewChatDialog.value = false
  userSearchKeyword.value = ''
  searchedUsers.value = []
}

onMounted(() => {
  // 初始化逻辑
  console.log('私聊组件已加载')
})
</script>

<style scoped>
.private-chat {
  height: 100vh;
  background: white;
}

.chat-layout {
  height: 100%;
  display: flex;
}

.new-chat-dialog {
  max-height: 500px;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 20px;
}

.search-section h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
  font-size: 0.875rem;
}

.search-input-group {
  display: flex;
  gap: 8px;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
}

.loading-users {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #6b7280;
  gap: 8px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.2s;
  gap: 12px;
  border: 1px solid transparent;
}

.user-item:hover {
  background-color: #f3f4f6;
  border-color: #e5e7eb;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-main-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
  color: #1f2937;
  font-size: 0.875rem;
}

.user-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-uid {
  font-size: 0.75rem;
  color: #6b7280;
}

.user-status {
  font-size: 0.75rem;
  padding: 2px 8px;
  border-radius: 12px;
}

.user-status.online {
  background: #ecfdf5;
  color: #10b981;
}

.user-status.offline {
  background: #f3f4f6;
  color: #6b7280;
}

.recent-users h4 {
  margin: 16px 0 12px 0;
  color: #1f2937;
  font-size: 0.875rem;
  font-weight: 600;
}

.empty-users {
  padding: 20px;
}
</style>